package modelLayer;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * LoanContainer is a class that holds information about loans
 */
public class LoanContainer {
    private ArrayList<Loan> loans;
    private static LoanContainer instance = null;
    private static int incrementedID = 0;
 
    /**
     * Create a loans ArrayList
     */
    private LoanContainer() {
        loans = new ArrayList<>();
    }
    
    /**
     * Singleton pattern which ensure that only one instance of a class is created.
     * @param instance The instance of the LoanContainer class.
     */
    public static LoanContainer getInstance() {
        if (instance == null) {
            instance= new LoanContainer();
        }
        return instance;
    }
    
    /**
     * Add a given new Loan object to loans ArrayList.
     * @param newLoan The new Loan object to be added in loans ArrayList
     */
    public void addLoan(Loan newLoan) {
        incrementedID++;
        newLoan.setID(incrementedID);
        loans.add(newLoan);
    }
    
    /**
     * Get a Loan object by a given ID.
     * @param ID The ID of the desired loan
     */
    public Loan getLoan(int ID) {
        for(Loan loan : loans) {
            if(loan.getID() == ID) {
                return loan;
            }
        }
        return null;
    }
    
    /**
     * Extend the period of the desired loan with a given new period
     * @param ID The ID of the desired loan to get his peiod updated.
     * @param newPeriod The new period of the loan.
     */
    public void extendLoan(int ID, String newPeriod){
        for(Loan loan : loans) {
            if(loan.getID() == ID) {
                loan.setPeriod(newPeriod);
            }
        }
    }
    
    /**
     * Delete the desired loan by a given ID.
     * @param ID The ID of the loan.
     */
    public void deleteLoan(int ID) {
        for(Iterator<Loan> i=loans.iterator();i.hasNext();) {
            Loan loan = i.next();
            if(loan.getID() == ID) {
                i.remove();
            }
        }
    }
    
    /**
     * Change the status of a loan
     * @param ID The ID of a loan to be completed
     */
    public void completeLoan(int ID) {
        for(Iterator<Loan> i=loans.iterator(); i.hasNext();){
            Loan loan = i.next();
            if(loan.getID() == ID) {
                loan.setState("complete");
            } 
        } 
    }
    
}
